<!--
 * @Description: 高德地图区域选择组件
 * @Author: chendingfengmail@163.com
 * @Date: 2022-01-12 10:18:45
 * @LastEditTime: 2022-01-12 17:40:51
 * @LastEditors: chendingfengmail@163.com
 * @Reference: 
-->
<!-- 高德地图区域选择组件 -->
<template>
  <el-amap
    ref="map"
    vid="amapDemo"
    :center="mapInfo.lnglat"
    :amap-manager="amapManager"
    :zoom="zoom"
    :events="events"
    :plugin="plugins"
  >
    <el-amap-polygon
      v-for="(polygon, index) in polygons"
      :key="index"
      :vid="index"
      :ref="`polygon_${index}`"
      :path="polygon.path"
      :editable="editable"
      fillColor="#2b83f9"
      fillOpacity="0.5"
      strokeWeight="4"
      strokeColor="#2b83f9"
      strokeOpacity="0.5"
      :events="polygonEvents"
    ></el-amap-polygon>
  </el-amap>
</template>

<script>
import { AMapManager } from 'vue-amap';
const amapManager = new AMapManager();
export default {
  name: 'ddMapArea',
  props: {
    // 搜索地址输入框dom元素的ID
    tipInputId: {
      type: String,
      default: () => {
        return '';
      },
    },
    // 地图默认中心点位置
    mapInfo: {
      type: Object,
      default: () => {
        return {
          address: '佛山市禅城区人民政府',
          lnglat: [113.122532, 23.009475],
        };
      },
    },
    // 是否为预览模式（true为禁止搜索和点选）
    preview: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  },
  data() {
    return {
      titleName: '详情',
      formLabelWidth: '100px',
      amapManager,
      map: {},
      zoom: 12,
      plugins: ['Geolocation', 'Autocomplete', 'PlaceSearch'],

      path: [],
      pIdx: 0,
      polygonPath: [],

      polygon: {},
      polygonEditor: null,
      isDraw: false,
      isEdit: false,
      editable: true,
      polygons: [],
      mapContextMenu: {},
    };
  },

  watch: {
    preview(val) {
      console.log('preview', val);
    },
  },

  computed: {
    events() {
      if (!this.preview) {
        return {
          init: (o) => {
            let _this = this;
            // 搜索定位
            if (_this.tipInputId != '') {
              _this.initMapByInput();
            }
            _this.map = _this.amapManager.getMap();
            this.mapContextMenu = new AMap.ContextMenu();
            // 右键添加区域
            this.mapContextMenu.addItem(
              '添加区域',
              function () {
                _this.addArea();
                _this.editable = true;
              },
              0,
            );
            _this.mapContextMenu.addItem(
              '结束编辑',
              function () {
                _this.endDraw();
                _this.editable = false;
                _this.$emit("handleEndDraw", _this.polygons)
              },
              1,
            );
          },
          click: (e) => {
            if (this.isDraw) {
              let arr = [e.lnglat.lng, e.lnglat.lat];
              this.polygons[this.pIdx].path.push(arr);
            }
          },
          rightclick: (e) => {
            this.mapContextMenu.open(this.map, e.lnglat);
          },
        };
      }
      return {};
    },
    polygonEvents() {
      return {
        init() {},
        click: (e) => {},
        rightclick: (e) => {
          this.mapContextMenu.open(this.map, e.lnglat);
        },
        dblclick: (e) => {
          this.editable = true;
        },
      };
    },
  },

  mounted() {},

  methods: {

    // 添加多边形区域
    addArea() {
      let _this = this;
      if (this.isDraw) {
        this.endDraw();
      }
      if (this.isEdit) {
        this.end();
      }
      let obj = {
        path: [],
        events: {
          click(e) {
            _this.clickEdit(_this, this);
          },
        },
      };
      this.polygons.push(obj);
      console.log('polygons', this.polygons);
      if (this.polygons.length > 0) {
        this.draw(this.polygons.length - 1);
      }
    },

    // 绘制多边形
    draw(idx) {
      if (this.isEdit) {
        this.end();
      }
      this.pIdx = idx;
      this.isDraw = true;
    },
    // 删除多边形区域
    del(idx) {
      this.polygons.splice(idx, 1);
    },

    // 结束绘制
    endDraw() {
      this.isDraw = false;
    },

    // 点击编辑
    clickEdit(vm, polygon) {
      if (vm.isDraw) {
        vm.endDraw();
      }
      if (vm.polygonEditor) {
        vm.end();
      }
      vm.isEdit = true;
      let map = vm.$refs.map.$$getInstance();
      //构造折线编辑对象，并开启折线的编辑状态
      let polygonEditor = new AMap.PolyEditor(map, polygon);
      vm.polygonEditor = polygonEditor;
      polygonEditor.open();
      //关闭多边形编辑polygonEditor.close()触发该方法；
      polygonEditor.on('end', function (event) {});
    },

    // 获取地址
    getFormattedAddress() {
      AMap.plugin('AMap.Geocoder', () => {
        let GeocoderOptions = {
          city: '全国',
        };
        let geocoder = new AMap.Geocoder(GeocoderOptions);
        geocoder.getAddress(this.mapInfo.lnglat, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            let locationInfo = {
              lnglat: this.mapInfo.lnglat,
              address: result.regeocode.formattedAddress,
            };
            // 将位置信息传递给父组件
            this.$emit('getLocationInfo', locationInfo);
          } else {
            this.$emit('getLocationInfo', '无法获取地址');
          }
        });
      });
    },

    // 输入检索地址
    initMapByInput() {
      AMap.plugin('AMap.Autocomplete', () => {
        let autoOptions = {
          city: '全国',
          input: this.tipInputId,
        };
        let autoComplete = new AMap.Autocomplete(autoOptions);
        AMap.event.addListener(autoComplete, 'select', (e) => {
          this.mapInfo.lnglat = [e.poi.location.lng, e.poi.location.lat];
          this.getFormattedAddress();
        });
      });
    },

  },
};
</script>
<style lang='scss' scoped>
</style>